﻿<?

// Enable full error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(-1);

// Sort function
function sortByName($item1, $item2)
{
    if ($item1['name'] == $item2['name']) return 0;
    return ($item1['name'] < $item2['name']) ? 1 : -1;
}

// Is this a valid request?
$mode = 'invalid';
if (isset($_REQUEST['key'])) $mode = 'unregister';
if (isset($_REQUEST['name']) && isset($_REQUEST['address'])) $mode = 'register';
if ($mode == 'register' || $mode == 'unregister') {
    $key = isset($_REQUEST['key']) ? $_REQUEST['key'] : $_REQUEST['address'];
	
	// Load existing information
	$entries = array();
	if (file_exists('servers.json')) {
		$text = file_get_contents('servers.json');
		$entries = json_decode($text, true);
	}
	
	// Find an existing entry to delete if possible, as well as registrations that have expired
	$newEntries = array();
	foreach ($entries as $entry) {
	    $entryKey = isset($entry['key']) ? $entry['key'] : $entry['address'];
		if ($entryKey != $key && $entry['registeredTime'] + 900 > time()) {
			$newEntries[] = $entry;
		}
	}
	
	// Add the new entry
	if ($mode == 'register') {
		$newEntries[] = array('key' => $key, 'name' => $_REQUEST['name'], 'address' => $_REQUEST['address'], 'registeredTime' => time());
	}
	
	// Save changes to the file
	usort($newEntries, 'sortByName');
	$json = json_encode($newEntries, JSON_PRETTY_PRINT);
	file_put_contents('servers.json', $json);
}

?>